<script setup lang="ts">
import XtxSwiper from '@/components/XtxSwiper.vue'
import CustomNavbar from './componets/CustomNavbar.vue'
import CategoryPanel from './componets//CategoryPanel.vue'
import HotPanel from './componets/HotPanel.vue'
import PageSkeleton from './componets/PageSkeleton.vue'
import { getHomeBannerAPI, getHomeCategoryAPI, getHomeHotAPI } from '@/services/home'
import { onLoad } from '@dcloudio/uni-app'
import { ref } from 'vue'
import type { BannerItem, CategoryItem, HotItem } from '@/types/home'
import type { XtxGuessInstance } from '@/types/component'
import { throttle } from 'lodash'
import { useGuessList } from '@/composables'

//获取和保存轮播图数据
const bannerlist = ref<BannerItem[]>([])
// const categoryList = ref([])
const getHomeBanner = async () => {
  const res = await getHomeBannerAPI()
  bannerlist.value = res.result
}
//获取和保存分类数据
const categorylist = ref<CategoryItem[]>([])
const getHomeCategoryList = async () => {
  const { result } = await getHomeCategoryAPI()
  categorylist.value = result
}
//获取和保存热门推荐数据
const hotlist = ref<HotItem[]>()
const getHotPanel = async () => {
  const { result } = await getHomeHotAPI()
  hotlist.value = result
}

//声明加载状态
const isLoad = ref(false)
onLoad(async () => {
  isLoad.value = true
  await Promise.all([getHomeBanner(), getHomeCategoryList(), getHotPanel()])
  isLoad.value = false
})
const { guessRef, onScrolltolower } = useGuessList()

//下拉刷新触发阀门
const isTriggered = ref(false)
//下拉刷新的回调函数
const onRefresherrefresh = async () => {
  //下拉刷新触发动画
  isTriggered.value = true
  //
  guessRef.value?.resetData()
  //等待数组里的异步任务执行完毕，await的意思就是等待当前任务执行完毕再执行下边的任务
  await Promise.all([getHomeBanner(), getHomeCategoryList(), getHotPanel(), guessRef.value?.getMore()])
  //下拉刷新关闭动画
  isTriggered.value = false
}
</script>

<template>
  <!-- 自定义导航栏 -->
  <CustomNavbar />

  <scroll-view refresher-enabled :refresher-triggered="isTriggered" @refresherrefresh="onRefresherrefresh" @scrolltolower="onScrolltolower" class="scroll-y" scroll-y>
    <PageSkeleton v-if="isLoad" />
    <template v-else>
      <!-- 自定义轮播图 -->
      <XtxSwiper :list="bannerlist" />
      <!-- 分类面板 -->
      <CategoryPanel :list="categorylist" />
      <!-- 热门推荐 -->
      <HotPanel :list="hotlist" />
      <!-- 猜你喜欢 -->
      <XtxGuess ref="guessRef" />
    </template>
  </scroll-view>
</template>

<style lang="scss">
page {
  height: 100%;
  background-color: #f7f7f7;
  display: flex;
  flex-direction: column;
  .scroll-y {
    flex: 1;
  }
}
</style>
